package com.cl.ks.controller;


import com.alibaba.fastjson.JSONObject;
import com.cl.ks.dto.KsRuleRequestModel;
import com.cl.ks.entity.KsDataType;
import com.cl.ks.entity.KsRule;
import com.cl.ks.service.KsRuleService;
import com.cl.mvc.controller.BaseController;
import com.cl.mvc.dto.CommonResult;

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("KsRule")
public class KsRuleController extends BaseController<KsRule> {
    private final KsRuleService ksRuleService;

    public KsRuleController(KsRuleService service) {
        super(service);
        ksRuleService = service;
    }

    @PostMapping("editPower")
    public CommonResult<KsRule> editPower(@RequestBody KsRuleRequestModel ksRule) {
        return CommonResult.success(ksRuleService.editPower(ksRule));
    }
    @RequestMapping(path = "/ruleTypesGroupCount", method = RequestMethod.GET)
    public CommonResult<JSONObject> ruleTypesGroupCount(@RequestParam("ruleTypes") List<String> ruleTypes, @RequestHeader(name = "Authorization", defaultValue = "") String auth) {
        return CommonResult.success(ksRuleService.ruleTypesGroupCount(ruleTypes, auth));
    }

    @GetMapping("copy")
    @ApiOperation("复制规则")
    public CommonResult copy(@RequestParam("ksRuleId") Integer ksRuleId) {
        Optional<KsRule> sourceRuleOptional = ksRuleService.findById(ksRuleId);
        if (!sourceRuleOptional.isPresent()) {
            return CommonResult.failed("规则不存在");
        }
        KsRule sourceRule = sourceRuleOptional.get();

        KsRule targetRule = new KsRule();
        BeanUtils.copyProperties(sourceRule,targetRule);
        targetRule.setFromRuleId(ksRuleId);
//        targetRule.setRuleName(sourceRule.getRuleName());
//        targetRule.setRuleExpressionJson(sourceRule.getRuleExpressionJson());
//        targetRule.setSystemCode(sourceRule.getSystemCode());
        return CommonResult.success(ksRuleService.save(targetRule));
    }

    @GetMapping("invoke")
    @ApiOperation("引用规则")
    public CommonResult invoke(@RequestParam("ksRuleId") Integer ksRuleId) {
        Optional<KsRule> ksRuleOptional = ksRuleService.findById(ksRuleId);
        if (!ksRuleOptional.isPresent()) {
            return CommonResult.failed("规则不存在");
        }
        KsRule ksRule = ksRuleOptional.get();
        ksRuleService.deleteById(ksRuleId);

        Integer fromRuleId = ksRule.getFromRuleId();
        return CommonResult.success(ksRuleService.findById(fromRuleId));
    }

}
